package com.xyh.reward_kotlin.fragments

import android.app.DownloadManager
import android.content.*
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.xyh.reward_kotlin.MainActivity
import com.xyh.reward_kotlin.R
import com.xyh.reward_kotlin.api.ApiCallback
import com.xyh.reward_kotlin.api.ApiClient
import com.xyh.reward_kotlin.api.RewardApi
import com.xyh.reward_kotlin.response.ApkVersionDto
import com.xyh.reward_kotlin.response.ResultDto
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.File

class HomeFragment : Fragment(R.layout.fragment_home) {

    private var downloadId: Long = 0
    private lateinit var downloadManager: DownloadManager
    private val rewardApi: RewardApi = ApiClient.client.create(RewardApi::class.java)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.d("home", "onViewCreated: 进入")

        val btnGoToCalc = view.findViewById<Button>(R.id.btnGoToCalc)
        btnGoToCalc.setOnClickListener {
            Log.d("home", "按钮点击: 跳转计算器")
            goToCalculator()
        }

        val btnCheckUpdate = view.findViewById<Button>(R.id.btnCheckUpdate)
        btnCheckUpdate.setOnClickListener {
            Log.d("home", "按钮点击: 检查更新")
            checkUpdateAndDownload()
        }

        downloadManager =
            requireContext().getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
        Log.d("home", "DownloadManager 初始化完成")

        // 注册广播监听下载完成
        registerDownloadReceiver()
    }

    private fun registerDownloadReceiver() {
        val filter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                requireActivity().registerReceiver(
                    downloadReceiver,
                    filter,
                    Context.RECEIVER_NOT_EXPORTED
                )
                Log.d("home", "广播注册完成 (Android 13+)")
            } else {
                requireActivity().registerReceiver(downloadReceiver, filter,Context.RECEIVER_NOT_EXPORTED)
                Log.d("home", "广播注册完成 (Android 12-)")
            }
        } catch (e: Exception) {
            Log.e("home", "注册下载广播失败: ${e.message}", e)
        }
    }

    private fun unregisterDownloadReceiver() {
        try {
            requireActivity().unregisterReceiver(downloadReceiver)
            Log.d("home", "已解绑下载广播")
        } catch (e: IllegalArgumentException) {
            Log.e("home", "解绑下载广播异常: ${e.message}")
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        Log.d("home", "onDestroyView: 解绑广播")
        unregisterDownloadReceiver()
    }

    private fun checkUpdateAndDownload() {
        Log.d("home", "开始检查更新")
        lifecycleScope.launch {
            try {
                rewardApi.getLastVersion().enqueue(object : ApiCallback<ResultDto<ApkVersionDto>>() {
                    override fun onSuccess(result: ResultDto<ApkVersionDto>) {
                        Log.d("home", "接口返回: $result")
                        val apkVersion = result.data
                        val currentVersionCode = requireContext().packageManager
                            .getPackageInfo(requireContext().packageName, 0).versionCode

                        Log.d("home", "当前版本: $currentVersionCode，最新版本: ${apkVersion?.versionCode}")

                        apkVersion?.versionCode?.let {
                            if (it > currentVersionCode) {
                                Log.d("home", "发现新版本: $it > $currentVersionCode")
                                apkVersion.downloadUrl?.let { url ->
                                    Log.d("home", "新版本下载地址: $url")
                                    downloadApkInBackground(url)
                                    Toast.makeText(requireContext(), "正在后台下载最新版本", Toast.LENGTH_SHORT).show()
                                }
                            } else {
                                Log.d("home", "已是最新版本")
                                Toast.makeText(requireContext(), "已是最新版本", Toast.LENGTH_SHORT).show()
                            }
                        }
                    }

                    override fun onError(errorMsg: String?) {
                        Log.e("home", "检查更新失败: $errorMsg")
                        Toast.makeText(requireContext(), "检查更新失败", Toast.LENGTH_SHORT).show()
                    }
                })
            } catch (e: Exception) {
                Log.e("home", "检查更新异常: ${e.message}", e)
            }
        }
    }

    private fun downloadApkInBackground(url: String) {
        // APK 保存路径
        val apkFile = File(requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "reward-app.apk")

        // 如果文件存在，删除旧文件
        if (apkFile.exists()) {
            val deleted = apkFile.delete()
            Log.d("home", "旧 APK 删除: $deleted, path=${apkFile.absolutePath}")
        }

        val request = DownloadManager.Request(Uri.parse(url))
            .setTitle("奖励计算器")
            .setDescription("正在下载最新版本...")
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
            .setDestinationUri(Uri.fromFile(apkFile)) // 指定下载目标文件
            .setAllowedOverMetered(true)
            .setAllowedOverRoaming(true)

        try {
            downloadId = downloadManager.enqueue(request)
            Log.d("home", "下载任务已加入队列, downloadId=$downloadId, url=$url, path=${apkFile.absolutePath}")

            // 开始轮询任务状态，避免广播丢失
            startCheckDownloadStatus()
        } catch (e: Exception) {
            Log.e("home", "下载任务加入失败: ${e.message}", e)
        }
    }

    private fun startCheckDownloadStatus() {
        lifecycleScope.launch {
            while (downloadId != 0L) {
                delay(2000)
                val query = DownloadManager.Query().setFilterById(downloadId)
                val cursor = downloadManager.query(query)
                if (cursor.moveToFirst()) {
                    val status = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS))
                    val reason = cursor.getInt(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_REASON))
                    val bytesDownloaded = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR))
                    val totalBytes = cursor.getLong(cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES))

                    Log.d("home", "轮询下载状态: id=$downloadId, status=$status, reason=$reason, $bytesDownloaded/$totalBytes")

                    when (status) {
                        DownloadManager.STATUS_SUCCESSFUL -> {
                            Log.d("home", "轮询确认下载完成")
                            installApk()
                            cursor.close()
                            return@launch
                        }
                        DownloadManager.STATUS_FAILED -> {
                            Log.e("home", "下载失败, reason=$reason")
                            cursor.close()
                            return@launch
                        }
                    }
                }
                cursor.close()
            }
        }
    }

    private val downloadReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            Log.d("home", "DownloadReceiver 收到广播: intent=$intent, context=$context")
            val id = intent?.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
            Log.d("home", "下载完成广播，收到ID: $id, 期望ID: $downloadId")
            if (id == downloadId) {
                Log.d("home", "下载ID匹配，准备安装APK")
                installApk()
            } else {
                Log.d("home", "下载ID不匹配，忽略广播")
            }
        }
    }

    private fun installApk() {
        val apkFile = File(requireContext().getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS), "reward-app.apk")
        Log.d("home", "准备安装APK，文件路径: ${apkFile.absolutePath}")

        if (!apkFile.exists()) {
            Log.e("home", "安装失败: 文件不存在")
            return
        }
        Log.d("home", "安装前文件大小: ${apkFile.length()}")

        val uri = FileProvider.getUriForFile(
            requireContext(),
            "${requireContext().packageName}.fileprovider",
            apkFile
        )
        Log.d("home", "FileProvider URI: $uri")

        val intent = Intent(Intent.ACTION_VIEW).apply {
            setDataAndType(uri, "application/vnd.android.package-archive")
        }
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
        try {
            startActivity(intent)
            Log.d("home", "启动安装Activity成功")
        } catch (e: Exception) {
            Log.e("home", "启动安装Activity失败: ${e.message}", e)
        }
    }

    private fun goToCalculator() {
        Log.d("home", "跳转到计算器页面")
        if (activity is MainActivity) {
            (activity as MainActivity).switchFragment(1)
            (activity as MainActivity).switchFragmentAndUpdateTab(1)
        }
    }
}
